package com.fs.chatx.module.chat.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fs.chatx.core.util.PromtUtil;
import com.fs.chatx.module.chat.enums.ModelProviderEnum;
import com.fs.chatx.module.chat.config.PromptConfig;
import com.fs.chatx.module.knowledge.service.MilvusOpService;
import io.github.pigmesh.ai.deepseek.core.DeepSeekClient;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionRequest;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;
import io.github.pigmesh.ai.deepseek.core.search.FreshnessEnums;
import io.github.pigmesh.ai.deepseek.core.search.SearchRequest;
import io.milvus.v2.service.vector.response.SearchResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DeepseekService
{

    @Autowired
    private DeepSeekClient deepSeekClient;


    @Autowired
    private MilvusOpService milvusService;

    @Autowired
    private PromptConfig promptConfig;


    //普通单次对话（流式）
    public Flux<ChatCompletionResponse> chat(String prompt)
    {
        return deepSeekClient.chatFluxCompletion(prompt);
    }

    //带历史记录多轮对话（流式）
    public Flux<ChatCompletionResponse> chatAdvanced(String prompt)
    {
        ChatCompletionRequest request = ChatCompletionRequest.builder()
                .model(ModelProviderEnum.DEEPSEEKV3.getModel().getModelName())
                // 添加用户消息
                .addUserMessage(prompt)
                // 添加助手消息，用于多轮对话
                .addAssistantMessage("上轮结果")
                // 添加系统消息，用于设置角色和行为
                .addSystemMessage("你是一个专业的助手")
                // 设置最大生成 token 数，默认 2048
                .maxTokens(2048)
                // 设置响应格式，支持 JSON 结构化输出
                //.responseFormat(...) // 可选
                // function calling
                //.tools(...) // 可选
                .build();
            return deepSeekClient.chatFluxCompletion(request);
    }


    //联网搜索
    public Flux<ChatCompletionResponse> chatSearch(String prompt)
    {
        // 指定联网搜索参数
        SearchRequest searchRequest = SearchRequest.builder()
                .enable(true)
                .freshness(FreshnessEnums.ONE_DAY)// 一天内的数据
                .summary(true) // 返回摘要
                .count(10) // 返回10条
                .page(1) // 第一页
                .build();
        return deepSeekClient.chatSearchCompletion(prompt,searchRequest);
    }

    //RAG搜素
    public Flux<ChatCompletionResponse> ragSearch(String prompt)
    {
        String askPrompt =prompt;
        List<List<SearchResp.SearchResult>> searchResults =milvusService.
                searchList("Medical_Knowledge_DataSet",prompt,"embedding");
        log.info("search results size: {}", searchResults.size());
        if(!searchResults.isEmpty()){
            List<String> resultList = new ArrayList<>();
            for (List<SearchResp.SearchResult> results : searchResults) {
                for (SearchResp.SearchResult topResult : results) {
                    String question=topResult.getEntity().get("question").toString();
                    String answer=topResult.getEntity().get("answer").toString();
                    resultList.add("问题: "+question+"  答案: "+answer);
                }
            }
            String contextStr = resultList.stream()
                    .map(para -> "- " + para)
                    .collect(Collectors.joining("\n"));
            // 渲染问答模版
            askPrompt = PromtUtil.renderPrompt(
                    promptConfig.getQaPrompt(),
                    Map.of("context", contextStr, "question", prompt)
            );
        }
        log.info("askPrompt: {}", askPrompt);
        ChatCompletionRequest request = ChatCompletionRequest
                .builder()
                .model(ModelProviderEnum.DEEPSEEKR1.getModel().getModelName())
                .addSystemMessage(promptConfig.getSystemPrompt())
                .addUserMessage(askPrompt)
                .build();
        // 调用 API 并获取响应
        StringBuffer fullResponse = new StringBuffer("");
        Flux<ChatCompletionResponse> response=  deepSeekClient.chatFluxCompletion(request)
                .doOnNext(r->{
                    String currentContent = r.choices().get(0).delta().content();
                    String finishReason = r.choices().get(0).finishReason();
                    fullResponse.append(currentContent);
                   // log.info("content: {},finishReason: {}", currentContent,finishReason);
                    if ("stop".equals(finishReason)) {
                        log.info("Final answer: {}", fullResponse.toString());
                    }
                 })
                .doOnError(error -> log.error("Streaming failed: {}", error.getMessage()))
                ;
        return response;
    }


    public  JSONArray structCheckReport(String report)
    {
        String systemPrompt = promptConfig.getStructPrompt();
        StringBuffer structPrompt =new StringBuffer("超声/CT/MRI医学报原始报告:\n ");
        structPrompt.append(report);
       return  JSON.parseArray(structReport(structPrompt.toString(),systemPrompt));
    }


    public  String  structReport(String report, String   systemPrompt)
    {
        systemPrompt=systemPrompt==null?promptConfig.getSystemPrompt():systemPrompt;
        log.info("report:{}", report);
        ChatCompletionRequest request = ChatCompletionRequest
                .builder()
                .model(ModelProviderEnum.QWEN7B.getModel().getModelName())
                .temperature(Double.valueOf(0.1))
                .addSystemMessage(systemPrompt)
                .addUserMessage(report)
                .build();
        // 调用 API 并获取响应
        ChatCompletionResponse fullResponse= deepSeekClient.chatCompletion(request)
                .execute();
        return  fullResponse.choices().get(0).message().content();
    }

}
